package com.bjgov.scoresys.util;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter {

	protected FilterConfig config;

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		res.setContentType("text/xml;charset=utf-8");
		req.setCharacterEncoding("utf-8");		
		HttpSession session = req.getSession();
		Pattern p = Pattern.compile("(\\.jpg|\\.gif|\\.bmp|\\.img|\\.jpeg|/pub/|/js/|login|register|/services/)");
		Matcher m = p.matcher(req.getRequestURI());
		if(m.find()) {
			chain.doFilter(request, response);
			return;
		}
		if (session.getAttribute("user") == null) {
			res.sendRedirect("/login.jsp");
		} else {
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
	}

}
